/**
 * 读取xml
 */
package com.wsj.util.tool;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

/**
 * @author fengbin
 *
 */
public class ReadExcelUtil 
{
	//excel文件路径
	private String filePath="";
	
	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}


	/*****
	 * 读取excel
	 * 注意将会导入excel中每个sheet页面的数据,所以不能有错误的数据出现
	 * 返回的是一个map组成的对象
	 */
	public List<Map> loadListByExcel(String[] columnName)
	{
		List<Map> retList=new ArrayList();
		//列的个数
		try 
		{
			Integer columnLength=columnName.length;
			
			if(filePath!=null && !filePath.equals(""))
			{
				Workbook wb = Workbook.getWorkbook(new File(filePath));
				Sheet sheet[] = wb.getSheets();
				
				//excel sheet数
				for (int i = 0; i < sheet.length; i++) 
				{
					Sheet stTemp = sheet[i];
//					 得到总列数
					int intColumns = stTemp.getColumns();
					// 得到总行数
					int intRows = stTemp.getRows();
					
                    //将第一行的标题屏蔽掉
					for (int j = 1; j < intRows; j++) 
					{
                        Map rowMap=new HashMap(columnLength);
						for (int m = 0; m < intColumns; m++) 
						{
							//获取单元格的数据
							Cell cell = stTemp.getCell(m, j);
							rowMap.put(columnName[m],cell.getContents());
						}
						retList.add(rowMap);
					}
					
				}
				
			}
			
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return retList;
	}
	
	
	
	/*******
	 * 测试excel读取
	 */
	public static void main(String[] args)
	{
		ReadExcelUtil readxml=new ReadExcelUtil();
		readxml.setFilePath("c:\\aa\\jxs.xls");
		List<Map> list=readxml.loadListByExcel(new String[]{"id","name"});
		
		System.out.println(list.size());
		
		for(int j=0;j<list.size();j++)
		{
			Map map=(HashMap)list.get(j);
			
			Set keySet = map.keySet();
			for(Iterator it=keySet.iterator();it.hasNext();)
			{
				String key = (String)it.next();
				System.out.println("行"+j+" : "+" key:"+key+" : value: "+map.get(key));
			}
		}
		
	}
	

}
